package com.pn.taikao.controller;

import com.pn.taikao.dto.ApiResponse;
import com.pn.taikao.dto.CreateResponse;
import com.pn.taikao.dto.PageResult;
import com.pn.taikao.dto.UserQueryRequest;
import com.pn.taikao.entity.User;
import com.pn.taikao.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 创建用户
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('TEACHER')")
    public ApiResponse<CreateResponse> create(@RequestBody User user) {
        Long id = userService.createUser(user);
        return ApiResponse.success(new CreateResponse(id));
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('TEACHER')")
    public ApiResponse<Void> update(@PathVariable("id") Long id, @RequestBody User user) {
        user.setId(id);
        userService.updateUser(user);
        return ApiResponse.success(null);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> delete(@PathVariable("id") Long id) {
        userService.deleteUser(id);
        return ApiResponse.success(null);
    }

    /**
     * 查询用户详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<User> detail(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        if (user == null) {
            return ApiResponse.error("用户不存在");
        }
        return ApiResponse.success(user);
    }

    /**
     * 分页查询用户列表
     */
    @PostMapping("/query")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<PageResult<User>> list(@RequestBody UserQueryRequest request) {
        // 处理默认值
        int page = (request.getPage() != null && request.getPage() > 0) ? request.getPage() : 1;
        int size = (request.getSize() != null && request.getSize() > 0) ? request.getSize() : 10;
        
        List<User> data = userService.list(request.getUsername(), request.getRoleType(), page, size);
        long total = userService.count(request.getUsername(), request.getRoleType());
        PageResult<User> pageResult = new PageResult<>(data, total, page, size);
        return ApiResponse.success(pageResult);
    }
}


